/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.order.service.impl.TuangouOrderServiceImpl
   Module Description   :

   Date Created      : 2011/8/27
   Original Author   : feeling.wang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.order.service.impl;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.order.service.TuangouOrderService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.shelf.entity.ShelfTuangou;
import com.yaodian100.ec.shelf.service.ShelfTuangouService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;

/**
 * @author feeling.wang
 * 
 */
public class TuangouOrderServiceImpl extends DomainServiceImpl<Orders> implements TuangouOrderService {
	@Autowired
	private OrderService orderService;
	@Autowired
	private ShelfTuangouService shelfTuangouService;
	@Autowired
	private Product2Service product2Service;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private CartOrdersService cartOrdersService;
	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private MemberService memberService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.order.service.TuangouOrderService#canBuy(java.lang.Long, java.lang.String)
	 */
	@Override
	public boolean canBuy(Long tuangouId, String memberId) throws CoreException {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("tuangouId", tuangouId);
		crit.addEq("memberId", memberId);
		int count = getDao().getListSize(crit).intValue();
		if (count > 0) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	@Transactional(readOnly = false)
	public CartOrders getTuangouCartOrders(Serializable oid) throws CoreException {
		CartOrders cart = cartOrdersService.get(oid);
		if (null != cart) {
			ShelfTuangou shelfTuangou = null;
			Product product = null;
			Iterator<CartOrderProduct> prodIter = cart.getCartOrderProducts().iterator();
			while (prodIter.hasNext()) {
				CartOrderProduct cop = prodIter.next();
				// 商品類別: 0主商品 1預購, 7限定立即购买
				shelfTuangou = shelfTuangouService.getActiveShelfTuangouByProductId(cop.getProdId());
				product = product2Service.get(cop.getProdId());
				boolean removeFlag = false;
				if (null == product || !"N".equals(product.getIsDelete())) {
					// 商品主檔不存在
					logger.warn("商品主檔不存在, cartId:{}. productId:{}", cart.getCartId(), cop.getProdId());
					baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderProdId=?", new Object[] { cop
							.getCartOrderProdId() });
					baseMgr.delete(cop);
					prodIter.remove();
				} else {
					cop.setIsScm(product.getIsScm());
					cop.setSupplierId(product.getSupplierId());

					int prodType = Integer.parseInt(cop.getProdTp());
					switch (prodType) {
					case 0:
					case 1:
					case 7:
						if (null == shelfTuangou) {
							// 一定會有上架檔
							logger.warn("Shelf不存在, cartId:{}. productId:{}", cart.getCartId(), cop.getProdId());
							removeFlag = true;
						}
						break;
					}
					if (removeFlag) {
						baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderProdId=?", new Object[] { cop
								.getCartOrderProdId() });
						baseMgr.delete(cop);
						prodIter.remove();
					} else {
						// 繼續檢核 detail
						Iterator<CartOrderProductDetail> detailIter = cop.getDetails().iterator();
						while (detailIter.hasNext()) {
							CartOrderProductDetail copd = detailIter.next();
							if (copd.getProdId().equals(product.getProductId())) {
								copd.setWeight(product.getProductWeight());
								copd.setVendId(product.getSupplierId());
								copd.setEcCost(product.getProductCost());
								cop.setUnitPrice(shelfTuangou.getPrice());
								copd.setAmount(shelfTuangou.getPrice());
							} else {
								Product p = (Product) baseMgr.get(Product.class, copd.getProdId());
								if (p != null) {
									copd.setWeight(p.getProductWeight());
									copd.setVendId(p.getSupplierId());
									copd.setEcCost(p.getProductCost());
								}
							}
						}
						cop.setEcCost(product.getProductCost());
						cop.setPmId(product.getPmID());
						cop.setPmGroup(product.getOrganizationPath());
					}
				}
			}
			cart.getAmount();
			cart.getWeightSum();
			cart.getMustPay();
		}
		return cart;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.shopping.service.CartOrdersService#getCart(java.lang.String, java.lang.String)
	 */
	@Override
	@Transactional(readOnly = false)
	public CartOrders getTuangouCartOrders(String memberId, String cartId) throws CoreException {
		CartOrders cart = null;
		if (StringUtils.isNotBlank(cartId)) {
			cart = getTuangouCartOrders(cartId);
		}
		if (null == cart && StringUtils.isNotBlank(memberId)) {
			cart = getTuangouCartOrders(memberId);
		}

		if (null != cart) {
			if (StringUtils.isNotBlank(cart.getMemberId())) {
				if (!cart.getMemberId().equals(memberId)) {
					logger.error("memberId incorrect, cartId;{}, memberId;{}", cart.getCartId(), memberId);
					cart = null;
				}
			}
		}
		return cart;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.order.service.TuangouOrderService#addTuangouProduct(java.lang.String, java.lang.String,
	 * java.lang.String, java.lang.Long, int)
	 */
	@Transactional(readOnly = false)
	public CartOrders addTuangouProduct(String memberId, String cartId, String productId, Long specId, int qty)
			throws CoreException {
		CartOrders entity = getTuangouCartOrders(memberId, cartId);
		if (null == entity) {
			throw new CoreException("errors.cart.null", cartId, memberId);
		}
		Product product = (Product) baseMgr.get(Product.class, productId);
		ShelfTuangou shelfTuangou = null;
		Specification spec = null;
		String categoryPath = "";
		// 检核商品主档是否存在
		if (null == product) {
			throw new CoreException("errors.product.null", productId);
		} else {
			// 找出商品主目录
			Category c = categoryService.get(Long.valueOf(product.getMainCategoryID()));
			categoryPath = c.getCategoryPath();

			Map<String, Specification> specMap = product2Service.getSpecifications(productId);
			if (MapUtils.isNotEmpty(specMap)) {
				spec = specMap.get(specId.toString());
			}
			if (null == spec) {
				throw new CoreException("errors.specification.null", productId);
			}
			SpecificationInventory inventory = product2Service.getSpecificationInventory(productId, specId);
			if (null == inventory) {
				throw new CoreException("errors.specification.inventory.null", specId.toString());
			}
			int minQty = NumberUtils.min(new int[] { spec.getMinCountPerOrder(), inventory.getInventory() });
			int maxQty = NumberUtils.min(new int[] { spec.getMaxCountPerOrder(), inventory.getInventory() });
			if (qty < minQty) {
				logger.error("集购数量未达最低购买限制, memberId:" + memberId + ",cartId:" + memberId + ",productId:" + productId
						+ ",minQty:" + minQty + "qty:" + qty);
				throw new CoreException("errors.specification.inventory.minQty");
			}
			if (qty > maxQty) {
				logger.error("集购数量已销售完毕, memberId:" + memberId + ",cartId:" + memberId + ",productId:" + productId + ",maxQty:"
						+ maxQty + "qty:" + qty);
				throw new CoreException("errors.specification.inventory.maxQty");
			}
			// 确认上架档
			shelfTuangou = shelfTuangouService.getActiveShelfTuangouByProductId(productId);
			if (null == shelfTuangou) {
				throw new CoreException("errors.shelf.null", productId);
			}
		}
		CartOrderProduct cop = null;
		CartOrderProductDetail copd = null;
		switch (product.getProductType()) {
		case 0:
		case 1:
		case 7:
			// 主
			cop = new CartOrderProduct(product, spec, shelfTuangou, categoryPath, qty);
			entity.addCartOrderProduct(cop);
			// logger.debug("op seq:{}", cop.getProdSeq());
			copd = new CartOrderProductDetail(product, spec, shelfTuangou, qty);
			cop.addDetail(copd);
			// logger.debug("opd seq:{}/{}", copd.getProdSeq(), copd.getDetailSeq());
			break;
		default:
			throw new CoreException("errors.product.type");
		}
		return saveTuangouCartOrders(entity);
	}

	@Override
	@Transactional(readOnly = false, timeout = 5)
	public CartOrders saveTuangouCartOrders(CartOrders entity) throws CoreException {
		return cartOrdersService.save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.order.service.TuangouOrderService#createTuangouCart(java.lang.String, java.lang.String,
	 * java.lang.Long, int)
	 */
	@Transactional(readOnly = false)
	public CartOrders createTuangouCart(String memberId) throws CoreException {
		CartOrders cart = new CartOrders();
		if (StringUtils.isNotBlank(memberId)) {
			Member member = memberService.get(memberId);
			cart.setMemberId(memberId);
			cart.setMemberName(StringUtils.defaultIfEmpty(member.getName(), member.getLoginId()));
			cart.setLoginId(member.getLoginId());
			cart.setReceiverEmail(member.getSendEmail());
		}
		cart.setCartId(java.util.UUID.randomUUID().toString());
		cart.setOrderDt(DateUtil.getCurrentTime());
		cart.setChannelSeq(0);
		cart.setChannel("yaodian100.com"); // ?!
		cart = cartOrdersService.save(cart);
		return cart;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaodian100.ec.order.service.TuangouOrderService#createTuangouOrderWithPay(com.yaodian100.ec.shopping.entity
	 * .CartOrders, java.util.Map)
	 */
	@Override
	@Transactional(readOnly = false)
	public Orders createTuangouOrderWithPay(CartOrders cart, Map<String, String> addonInfo, Map<String, String> payment)
			throws CoreException {
		return orderService.createOrderWithPay(cart, addonInfo, payment);
	}

	// check contactName
	public boolean isInteger(String input) {
		try {
			Integer.parseInt(input);
			if (input.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	// check addr
	public boolean isInteger2(String input) {
		try {
			Integer.parseInt(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}